package com.huaru.message.utile;
import java.io.*;
import java.util.Properties;
import java.util.regex.Pattern;

public class Config {
    private static Properties properties;
	private static long lastTime;
	private static Properties  getProperties(){
		if(System.currentTimeMillis()-lastTime>3600000||properties==null){
			InputStreamReader is = null;
			properties = new Properties();
			try {
//				//获取java的jar包所在的文件夹根目录
				//读取jar包所在文件根目录的config.properties
				//String path = Config.class.getProtectionDomain().getCodeSource().getLocation().getFile();
				//if (path.contains("jar")) {
				//	path = path.substring(0, path.lastIndexOf("."));
				//	path = path.substring(0, path.lastIndexOf("/")).replace("file:/", "");
				//}
				////获取java的jar包所在的文件夹根目录下的config.properties配置文件
				//path = path + "//config.properties";
				//File file = new File(path);
				////转换为文件流
				//InputStream inputStream  = new FileInputStream(file);
				//is = new InputStreamReader(inputStream, "UTF-8");
				is = new InputStreamReader(Config.class.getClassLoader().getResourceAsStream("config.properties"),"UTF-8");
				properties.load(is);
				lastTime = System.currentTimeMillis();
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				if(is!=null){
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return properties;
	}
	public static String getString(String key){
		//打jar包时文件默认上传在jar包所在的根目录
		//if(key.equals("file.path")) {
		//	if (StringUtil.isEmpty(getProperties().getProperty(key))) {
		//		String path = Config.class.getProtectionDomain().getCodeSource().getLocation().getFile();
		//		if (path.contains("jar")) {
		//			path = path.substring(0, path.lastIndexOf("."));
		//			path = path.substring(0, path.lastIndexOf("/")).replace("file:/", "");
		//		}
		//		return path + "//root//";
		//	} else {
		//		return getProperties().getProperty(key);
		//	}
		//} else {
		//	return getProperties().getProperty(key);
		//}
		return getProperties().getProperty(key);
	}
	
	public static int getInt(String key){
		if(Pattern.matches("^[0-9]+$", getProperties().getProperty(key))){
			return Integer.parseInt(getProperties().getProperty(key));
		}else{
			return -1;
		}
		
	}
}
